/*
 * Copyright (c) 2015-2018 Sfkj Science And Technology Co.,Ltd.
 * All Rights Reserved.
 * This software is the confidential and proprietary information of
 * Sfkj Science And Technology Co.,Ltd.
 * ("Confidential Information").You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Sfkj.
 */
package com.sfkj.walk.command.note;

import com.sfkj.walk.api.note.CreateNoteCommand;
import com.sfkj.walk.api.note.DeleteNoteCommand;
import com.sfkj.walk.api.note.NoteCreatedEvent;
import com.sfkj.walk.api.note.NoteDeletedEvent;
import com.sfkj.walk.command.activity.ActivityMember;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.commandhandling.model.AggregateIdentifier;
import org.axonframework.commandhandling.model.AggregateMember;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.spring.stereotype.Aggregate;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

import static org.axonframework.commandhandling.model.AggregateLifecycle.apply;
import static org.axonframework.commandhandling.model.AggregateLifecycle.markDeleted;

@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Getter
@Aggregate
@EqualsAndHashCode(of = "id")
public class Note {

    @AggregateIdentifier
    private String id;
    @Getter
    private String activityId;

    @AggregateMember
    private List<ActivityMember> members = new ArrayList<>();


    @CommandHandler
    public Note(CreateNoteCommand command) {
        NoteCreatedEvent event = new NoteCreatedEvent();
        BeanUtils.copyProperties(command, event);
        apply(event);
    }

    @CommandHandler
    public void delete(DeleteNoteCommand command) {
        NoteDeletedEvent event = new NoteDeletedEvent();
        event.setId(getId());
        event.setActivityId(getActivityId());

        apply(event);
    }


    @EventSourcingHandler
    public void on(NoteCreatedEvent event) {
        this.id = event.getId();
        this.activityId = event.getActivityId();
    }

    @EventSourcingHandler
    public void on(NoteDeletedEvent event) {
        markDeleted();
    }

}